package com.yoosora.common.mode.response;

import java.util.Collections;
import java.util.List;

/**
 * @author yoosora
 */
public class PageableResponse<T> extends AbstractResponse {
	private static final long serialVersionUID = 1911199693598276193L;
	private int page;
	private int rows;
	private long totalCount;
	private long totalPages;
	private List<T> list;

	public PageableResponse() {
	}

	public int getPage() {
		return this.page;
	}

	public int getRows() {
		return this.rows;
	}

	public long getTotalCount() {
		return this.totalCount;
	}

	public long getTotalPages() {
		return this.totalPages;
	}

	public List<T> getList() {
		return this.list;
	}

	public static <T> Builder<T> newBuilder(int page, int rows) {
		return new Builder(page, rows);
	}

	public static class Builder<T> extends AbstractResponse.Builder<SingleResponse.Builder<T>> {
		private int page;
		private int rows;
		private long totalCount;
		private List<T> list;

		private Builder(int page, int rows) {
			this.page = page;
			this.rows = rows;
		}

		public Builder<T> succ(List<T> list, long totalCount) {
			this.errcode = 0;
			this.list = list;
			this.totalCount = totalCount;
			return this;
		}

		public PageableResponse<T> build() {
			PageableResponse<T> resp = new PageableResponse();
			resp.errcode = this.errcode;
			resp.errmsg = this.errmsg;
			resp.page = this.page;
			resp.rows = this.rows;
			resp.totalCount = this.totalCount;
			if (this.totalCount == 0L) {
				resp.totalPages = 1L;
			} else {
				resp.totalPages = this.totalCount % (long)this.rows == 0L ? this.totalCount / (long)this.rows : this.totalCount / (long)this.rows + 1L;
			}

			if (this.list == null) {
				resp.list = Collections.emptyList();
			} else {
				resp.list = this.list;
			}

			return resp;
		}
	}
}
